package com.ly.share.juc.cas;

import sun.misc.Unsafe;

import java.util.concurrent.CountDownLatch;

/**
 * @author icanci
 * @since 1.0 Created in 2022/06/05 21:44
 */
public class RequestDemo2 {
    static int count = 0;

    public static void main(String[] args) throws Exception {

        Class<Unsafe> unsafeClass = Unsafe.class;
        CountDownLatch latch = new CountDownLatch(100);
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    for (int i1 = 0; i1 < 10; i1++) {
                        try {
                            request();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                } finally {
                    latch.countDown();
                }
            }, String.valueOf(i)).start();
        }
        latch.await();
        System.out.println(count);
    }

    public static synchronized boolean compareAndSwap(int expectCount, int newCount) {
        if (getCount() == expectCount) {
            count = newCount;
            return true;
        }
        return false;
    }

    public static int getCount() {
        return count;
    }

    public static void request() throws InterruptedException {
        Thread.sleep(5);
        int expectCount;
        while (!compareAndSwap(expectCount = getCount(), expectCount + 1)) {
        }

    }
}
